'use strict';

const Service = require('egg').Service;

class MysqlService extends Service {
  /**
   * 通过配置的version更新数据库结构
   */
  async updateMysqlByVersion() {
    const { sequelize: { version } } = this.app.config;
    const lock = await this.app.redis.incr('mysqlLock');
    if (Number(lock) === 1) {
      await this.app.redis.del('mysqlLock');
      const nowVersion = await this.app.redis.get('nowVersion') || 0;
      if (Number(version) > Number(nowVersion)) {
        await this.app.redis.set('nowVersion', version + 1);
        await this.app.model.sync({ alter: true });
      }
    }
  }

  /**
   * 添加初始数据
   * 如果不存在数据，则添加初始数据
   */
  async initMysql() {
    // eslint-disable-next-line global-require
    const initData = require('../../config/defaultdata');
    const transaction = await this.app.model.transaction();
    try {
      const { data: { clientData, userData } } = initData;
      const clientExist = await this._clientModel.findOne({
        where: {
          name: clientData.name,
        },
      });
      if (!clientExist) {
        await this._clientModel.upsert(clientData, {
          transaction,
        });
      }
      const userExist = await this.app.model._userModel.findByName(userData.name);
      if (!userExist) {
        userData.hashedPassword = this.ctx.helper.hash(userData.password);
        await this._userModel.upsert(userData, {
          transaction,
        });
      }
      await transaction.commit();
      return {
        result: 0,
      };
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }
}

module.exports = MysqlService;
